package top.linyuxb.lycloud.admin.web.interceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.service.impl.LoginService;
import top.linyuxb.lycloud.admin.web.annotation.PermissionLimit;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc: 权限拦截, 简易版
 */
@Component
public class PermissionInterceptor extends WebRequestHandlerInterceptorAdapter {

    @Resource
    private LoginService loginService;

    public PermissionInterceptor(WebRequestInterceptor requestInterceptor) {
        super(requestInterceptor);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }

        // if need login
        boolean needLogin = true;
        boolean needAdminuser = false;
        HandlerMethod method = (HandlerMethod) handler;
        PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
        if (permission != null) {
            needLogin = permission.limit();
            needAdminuser = permission.adminuser();
        }

        if (needLogin) {
            LyCloudUserEntity loginUser = loginService.ifLogin(request);
            if (loginUser == null) {
                response.sendRedirect(request.getContextPath() + "/toLogin");
                //request.getRequestDispatcher("/toLogin").forward(request, response);
                return false;
            }
            if (needAdminuser && loginUser.getPermission() != 1) {
                throw new RuntimeException("权限拦截");
            }
            request.setAttribute(LoginService.LOGIN_IDENTITY, loginUser);
        }

        return super.preHandle(request, response, handler);
    }

}
